package com.yuewen.mall.common.mallcacher;

import com.google.gson.reflect.TypeToken;
import com.yuewen.mall.common.redisclient.RedisClient;
import com.yuewenmall.common.baseentities.common.config.RedisServerConfig;
import com.yuewenmall.common.baseentities.enumerate.ConfigFileNames;
import com.yuewenmall.common.utilities.ConfigUtility;
import com.yuewenmall.common.utilities.FileUtility;
import com.yuewenmall.common.utilities.JsonUtility;
import com.yuewenmall.common.utilities.ValidatorUtility;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by liwei.b on 2016/6/27.
 */
public class CommonCacherManager {
    protected static RedisClient redisClient = new RedisClient();

    static {
        String strRedisServerConfigFilePath = ConfigUtility.getConfigFilePath(ConfigFileNames.RedisServerConfigFile);
        if (ValidatorUtility.isNullOrEmpty(strRedisServerConfigFilePath)) {
            System.out.println(strRedisServerConfigFilePath + " => redis server config content is empty or file not found!");
        } else {
            String strJsonConfig = FileUtility.Read(strRedisServerConfigFilePath);
            if (!ValidatorUtility.isNullOrEmpty(strJsonConfig)) {
                List<RedisServerConfig> servers = JsonUtility.FromJsonString(strJsonConfig, new TypeToken<ArrayList<RedisServerConfig>>() {
                }.getType());
                System.out.println(JsonUtility.ToJsonString(servers, true));
                if (servers == null || servers.size() <= 0) {
                    System.out.println(strRedisServerConfigFilePath + " => redis server config content format is error or no any servers!");
                } else {
                    redisClient = new RedisClient(servers.get(0).getHost(), servers.get(0).getPort(), servers.get(0).getPassword());
                    System.out.println(strRedisServerConfigFilePath + " => redis server init successfully!");
                }
            } else {
                System.out.println(strRedisServerConfigFilePath + " => redis server config content is empty!");
            }
        }
    }

    public <T> T get(Class<T> dataType, String cacheKey) {
        return redisClient.get(dataType, cacheKey);
    }

    public String set(String cacheKey, Object value) {
        return redisClient.setObject(cacheKey, value);
    }

    public String set(String cacheKey, Object value, int timespan) {
        return redisClient.setObject(cacheKey, value, timespan);
    }

    public long delete(String cacheKey) {
        return redisClient.delete(cacheKey);
    }

    public boolean isKeyExist(String key) {
        return redisClient.isKeyExist(key);
    }
}
